package com.ext.aic.components;

import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.StrikethroughSpan;
import android.text.style.StyleSpan;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MarkdownParser {

    public static SpannableStringBuilder parse(String text) {
        SpannableStringBuilder ssb = new SpannableStringBuilder();
        Pattern pattern = Pattern.compile(
                "\\*\\*(.*?)\\*\\*" + // 加粗**
                        "|__(.*?)__" +        // 加粗__
                        "|\\*(.*?)\\*" +      // 斜体*
                        "|_(.*?)_" +          // 斜体_
                        "|~~(.*?)~~"          // 删除线
        );
        Matcher matcher = pattern.matcher(text);
        int lastEnd = 0;

        while (matcher.find()) {
            int start = matcher.start();
            int end = matcher.end();
            // 添加之前的普通文本
            ssb.append(text.substring(lastEnd, start));

            // 提取内容和样式类型
            String content = null;
            String[] groups = new String[matcher.groupCount()];
            for (int i = 1; i <= matcher.groupCount(); i++) {
                groups[i - 1] = matcher.group(i);
            }
            int style = -1; // 0: bold, 1: italic, 2: strike

            if (groups[0] != null || groups[1] != null) {
                content = groups[0] != null ? groups[0] : groups[1];
                style = 0;
            } else if (groups[2] != null || groups[3] != null) {
                content = groups[2] != null ? groups[2] : groups[3];
                style = 1;
            } else if (groups[4] != null) {
                content = groups[4];
                style = 2;
            }

            if (content != null) {
                int ssbStart = ssb.length();
                ssb.append(content);
                int ssbEnd = ssb.length();
                applySpan(ssb, style, ssbStart, ssbEnd);
            }
            lastEnd = end;
        }
        // 添加剩余文本
        ssb.append(text.substring(lastEnd));
        return ssb;
    }

    private static void applySpan(SpannableStringBuilder ssb, int style, int start, int end) {
        switch (style) {
            case 0: // 加粗
                ssb.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                break;
            case 1: // 斜体
                ssb.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                break;
            case 2: // 删除线
                ssb.setSpan(new StrikethroughSpan(), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                break;
        }
    }
}